/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.widgets.listview;

import java.io.Serializable;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.phonebooksharing.android.R;
import com.phonebooksharing.android.activities.dashboard.MessageReaderActivity;
import com.phonebooksharing.android.util.ContactUtils;
import com.phonebooksharing.android.util.GeneralUtils;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.GalleryUtilities;
import com.phonebooksharing.android.widgets.drawable.FastBitmapDrawable;
import com.phonebooksharing.dto.dashboard.DashboardReaderItem;
import com.phonebooksharing.dto.friend.ContactItem;
import com.phonebooksharing.dto.msg.TextMessageItem;
import com.phonebooksharing.dto.msg.VoiceMessageItem;

@SuppressWarnings("unchecked")
public class MessageListView extends ReadableListView {
    
    private LayoutInflater inflater;
    private Bitmap text, voice;
    public MessageListView(Context dv, int qty, TextView counter) {
        super(dv, qty, counter);
        inflater = LayoutInflater.from(getContext());

        //TODO: use imageutils to cache and load this
        Resources r = getContext().getResources();
        
        text = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(r, R.drawable.dash_messages), 24, 24, true);
        voice = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(r, R.drawable.audio_play), 25, 25, true);
        
        setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> av, View v, int loc, long idd) {
                final DashboardReaderItem<ContactItem> d = (DashboardReaderItem<ContactItem>)adapter.getItem(loc);
                final ContactItem f = d.getItem();
                final Context c = getContext();
                final Intent i = new Intent(c, MessageReaderActivity.class);
                
                if(f instanceof TextMessageItem) {
                    TextMessageItem t = (TextMessageItem)f;
                    i.setAction(MessageReaderActivity.READ_TEXT);
                    i.putExtra(MessageReaderActivity.TITLE, t.title);
                    i.putExtra(MessageReaderActivity.TEXT, t.text);
                } else {
                    VoiceMessageItem vi = (VoiceMessageItem)f;
                    final Uri url = Uri.parse(String.format("http:" + Global.MESSAGE_SERVLET_URL, "a" /*ac*/, "" /*t*/, vi.voiceMessageID /*q*/, "" /*mt*/));
                    i.setAction(MessageReaderActivity.READ_AUDIO);
                    i.setDataAndType(url, "audio/*");
                }
                i.putExtra(MessageReaderActivity.ITEM_OBJ, f);
                
                //common stuff
                long id;
                if((id = f.andID) > 0) {
                    FastBitmapDrawable fb = GalleryUtilities.getFromContactCache(id);
                    if(fb == null) {
                        fb = GalleryUtilities.noPictureBitmap;
                    }
                    i.putExtra(MessageReaderActivity.FRIEND_ICON, fb.getBitmap());
                } else {
                    id = f.iconID;
                    i.putExtra(MessageReaderActivity.FRIEND_ICON, GalleryUtilities.noPictureBitmap.getBitmap());
                }
                i.putExtra(MessageReaderActivity.FRIEND_NAME, f.name);
                i.putExtra(MessageReaderActivity.FRIEND_STATUS, f.status);
                i.putExtra(MessageReaderActivity.FRIEND_LOCATION, f.location);
                i.putExtra(MessageReaderActivity.SENT_WHEN, d.getWhen());
                i.putExtra(MessageReaderActivity.DASHBOARD_ID, d.getId());
                i.putExtra(MessageReaderActivity.FRIEND_ID, f.andID);
                i.putExtra(MessageReaderActivity.DASHBOARD_READER_ITEM, d);
                c.startActivity(i);
            }
        });
    }
    
    @Override
    public View getConvertView(View cv, Object dto, int position, ViewGroup parent) {
       ViewHolder holder;
       
       final DashboardReaderItem<ContactItem> d = (DashboardReaderItem<ContactItem>)dto;
       final ContactItem cache = d.getItem();
       
       if (cv == null) {
           cv = inflater.inflate(R.layout.list_item_3lines_check, null);

           holder = new ViewHolder();
           holder.icon = (ImageView) cv.findViewById(android.R.id.icon);
           holder.border = (View) cv.findViewById(android.R.id.background);
           holder.name = (TextView) cv.findViewById(R.id.name);
           holder.time = (TextView) cv.findViewById(R.id.date);
           holder.text1 = (TextView) cv.findViewById(R.id.title);
           holder.text2 = (TextView) cv.findViewById(R.id.text);
           
           holder.type = (ImageView) cv.findViewById(R.id.type);
           holder.check = (ImageView) cv.findViewById(R.id.check);
           
           holder.container = cv.findViewById(R.id.container);
           holder.container.setOnClickListener(checkListener);
           
           cv.setTag(holder);
       } else {
           holder = (ViewHolder) cv.getTag();
       }
       holder.container.setTag(d);
       
       ContactUtils.setContactPhoto(this, cache, holder.icon, holder.border, position);
       
       if(cache instanceof VoiceMessageItem) {
           holder.type.setImageBitmap(voice);
           VoiceMessageItem v = (VoiceMessageItem)cache;
           final String t = v.title;
           if(TextUtils.isEmpty(t)) {
               holder.text2.setText("(" + v.length + ")");
           } else {
               holder.text1.setText("\"" + t + "\"");//length
               holder.text2.setText("(" + v.length + ")");
           }
       } else {//TextMessageItem
           holder.type.setImageBitmap(text);
           TextMessageItem t = (TextMessageItem)cache;
           holder.text1.setText(t.title);
           holder.text2.setText(t.text);
       }
       
       if(d.isCrossed()) {
           holder.check.setImageState(new int[] { android.R.attr.state_checked }, true);
       } else {
           holder.check.setImageState(new int[] {  }, true);
       }
       
       holder.id = d.getId();
       holder.name.setText(cache.name);
       holder.time.setText("(" + DateUtils.formatElapsedTime(
               (GeneralUtils.calculateGmtTimeInMilis(System.currentTimeMillis()) - 
                GeneralUtils.calculateGmtTimeInMilis(d.getWhen()) )/1000) + ")");
       
       return cv;
    }
    
    @Override
    public String getLoadDataURL() {
        return String.format(Global.DASHBOARD_SERVLET_URL, "m" /*ac*/, -1 /*q*/, currentPage++ /*p*/, Global.PAGINATOR_PAGE_SIZE /*ps*/);
    }

    @Override
    public Serializable getObject2Send() {
        return Global.authItem;
    }
}
